﻿
using Hwh_Shop.Models;
using Hwh_Shop.Models.Database;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Xml.Linq;
using Hwh_Shop.Service;

namespace Hwh_Shop.Controllers
{
	/// <summary>
	/// 用户模块
	/// </summary>
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class UserController : ControllerBase
	{
		// 定义数据库上下文  类型		 变量名
		// 私有    只读类型（它仅可以在构造函数里赋值，赋值后不能改变）
		private readonly Hwh_ShopContext _db;
		// 注入JWT服务
		private readonly IJWTService _jwtService;

        /// <summary>
        /// 构造方法 构造注入
        /// 构造函数（UserController类初始化第一个访问的函数）
        /// 把数据库上下文初始化
        /// 从IOC容器（管理对象的容器）获取db对象（Hwh_ShopContext类型）
        /// </summary>
        /// <param name="db"></param>
        /// <param name="jwtService"></param>
        public UserController(Hwh_ShopContext db, IJWTService jwtService)
		{
			_db = db;
			_jwtService = jwtService;
		}

		/// <summary>
		/// 用户注册
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		public string Register(UserRegister user)
		{
			//判断两次密码是否一致
			if (user.Password != user.CifrgPassword)
			{
				return "两次密码不一致";
			}
			var newUser = new User
			{
				Tel = user.Tel,
				Password = user.Password,
				Createtime = System.DateTime.Now
			};

			var row = _db.Users.Count(x => x.Tel == user.Tel);
			if (row > 0)
			{
				return "该手机号已注册";
			}
			_db.Users.Add(newUser);
			return _db.SaveChanges() > 0 ? "注册成功" : "注册失败";
		}

		/// <summary>
		/// 用户登录
		/// </summary>
		/// <param name="tel" example="12345678901">请输入手机号</param>
		/// <param name="pwd">请输入密码</param>
		/// <returns></returns>
		[HttpGet]
		public string Login(string tel, string pwd)
		{
			var row = _db.Users.Count(x => x.Tel == tel && x.Password == pwd);
			if (row > 0)
			{
				var userid = _db.Users.FirstOrDefault(x => x.Tel == tel).Id;
				return "登陆成功："+"您的token：" + _jwtService.CreateToken(tel, userid);
			}
			else
			{
				return "账号或密码错误";
			}
		}

		/// <summary>
		/// 个人中心
		/// </summary>
		[HttpGet]
		[Authorize]//标签 接口需要授权
		public List<string> ShowUser()
		{
			//获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
			var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
																												 // 获取用户的头像
			var userPhoto = _db.Users.FirstOrDefault(x => x.Tel == userTel).Photo;
			// 获取用户的昵称
			var userName = _db.Users.FirstOrDefault(x => x.Tel == userTel).Name;
			// 查询用户各订单状态的数量
			var orderCount_No = _db.Orders.Where(x => x.OrderUser == userTel && x.OrderState == "待发货").Select(x => x.OrderNo).Distinct().Count();
			var orderCount_Yes = _db.Orders.Where(x => x.OrderUser == userTel && x.OrderState == "已发货").Select(x => x.OrderNo).Distinct().Count();
			var orderCount_All = _db.Orders.Where(x => x.OrderUser == userTel).Select(x => x.OrderNo).Distinct().Count();

			if (userName == null)
			{
				userName = userTel;
			}

			//新建一个列表，用于存储用户的个人信息，并返回
			List<string> list = new List<string>();
			list.Add("用户头像：" + userPhoto);
			list.Add("用户昵称：" + userName);
			list.Add("全部订单数量：" + orderCount_All.ToString());
			list.Add("待发货：" + orderCount_No.ToString());
			list.Add("已发货：" + orderCount_Yes.ToString());
			return list;
		}

		/// <summary>
		/// 用户信息修改
		/// </summary>
		/// <param name="photo">请输入新的头像地址</param>
		/// <param name="name">请输入新的昵称</param>
		/// <returns></returns>
		[HttpGet]
		[Authorize]//标签 接口需要授权
		public string UpdateUser(string photo, string name)
		{
			//获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
			var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
			_db.Users.FirstOrDefault(x => x.Tel == userTel).Photo = photo;
			_db.Users.FirstOrDefault(x => x.Tel == userTel).Name = name;
			var row = _db.SaveChanges();
			if (row > 0)
			{
				return "修改成功";
			}
			else
			{
				return "修改失败";
			}
		}
	}
}
